package com.teichmann.core.targets.online;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.OnlinePage;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;
import com.teichmann.core.util.CrawlerUtils;


@Url(value = "http://www.autocarro.com.br/autobusca.php")
public class AutoCarro implements OnlinePage {
	
	Logger logger = Logger.getLogger(this.getClass().getSimpleName());
	HttpClient client;
	
	ArrayList<Car> cars = new ArrayList<Car>();
	NodeVisitor visitor = new NodeVisitor() {
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("tr".equalsIgnoreCase(name)
					&& (tag.getAttribute("bgcolor") != null 
							&& (tag.getAttribute("bgcolor").contains("#c0c0c0".toUpperCase()) 
									|| tag.getAttribute("bgcolor").contains("#FFFFFF"))
									&& tag.getAttribute("HEIGHT").equals("30"))) {
				
				cars.add(extractInformation(tag));
				
			}
		}
	};


	
	public ArrayList<Car> performSearch(String parameter) throws IOException {

		logger.debug("Entering "+this.getClass().getSimpleName());
		
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("AutModelo", parameter);
		parameters.put("Tipo", "REV");
		
		String responseBody =  ConnectionUtils.post( client, this.getClass().getAnnotation(Url.class).value(), parameters);
		parse(responseBody);
		
		int numberOfPages =  org.apache.commons.lang.StringUtils.countMatches(responseBody, "autobusca.php?pagina");

		if (numberOfPages ==0){
			if (org.apache.commons.lang.StringUtils.countMatches(responseBody, "autobuscaDet.php?") > 0 )
				numberOfPages = 1;
		}
		
		for (int x=1; x < numberOfPages; x++){
			responseBody =  ConnectionUtils.get(client, "http://www.autocarro.com.br/autobusca.php?pagina="+x+"&Tipo=REV&AutModelo="+parameter);
			parse(responseBody);
		}

		return cars;

	}

	private void parse(String responseBody) {
		Parser parser = new Parser(new Lexer(responseBody));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			e.printStackTrace();
		}
	}

	public Car extractInformation(Tag line) {
		Car car = new Car();
		int count = 1;
		try {

			NodeList details = line.getChildren();
			details = details.extractAllNodesThatMatch(new NodeFilter() {
				public boolean accept(Node arg0) {
					if (arg0 instanceof TableColumn) {
						return true;

					}

					return false;
				}

			});

			Pattern intOnly = Pattern.compile("\\d*");
	
			car.setModelo(CrawlerUtils.removeUnusedFields(details.elementAt(0).getChildren().elementAt(1).getChildren().elementAt(0).getText()));
			car.setPlaca(CrawlerUtils.removeUnusedFields(details.elementAt(1).getChildren().elementAt(1).getChildren().elementAt(0).getText()));

			// ano fabricacao
			String anoModelo =  CrawlerUtils.removeUnusedFields(details.elementAt(2).getChildren().elementAt(1).getChildren().elementAt(0).getText());
			Matcher matcher = intOnly.matcher(anoModelo.trim());
			if (matcher.find()) {
				car.setAnoModelo(new Integer(matcher.group()));
			} else {
				car.setAnoModelo(new Integer(anoModelo));
			}
			car.setAnoFabricacao(car.getAnoModelo());
			car.setCor(CrawlerUtils.removeUnusedFields(details.elementAt(3).getChildren().elementAt(1).getChildren().elementAt(0).getText()));
			car.setCombustivel(CrawlerUtils.removeUnusedFields(details.elementAt(4).getChildren().elementAt(1).getChildren().elementAt(0).getText()));
			car.setValor(CrawlerUtils.removeUnusedFields(details.elementAt(6).getChildren().elementAt(1).getChildren().elementAt(0).getText()));
			car.setUrl("http://www.autocarro.com.br/"+ ((LinkTag) details.elementAt(0).getChildren().elementAt(1)).getLink());
			car.setRevenda(new Seller(this.getClass().getSimpleName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;
		
		
	}

	public ArrayList<Car> performSearch(String parameter, HttpClient client)
			throws IOException {
		this.client = client;
		return performSearch(parameter);
	}


}
